<script setup>
import { onBeforeMount } from 'vue';
import { useRoute } from 'vue-router';
import { ref } from 'vue';
import service from '@/utils/request.utils';
import { Upload, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import FileSourceItem from '@/components/hub/sub/FileSourceItem.vue'
import DatabaseSourceItem from '@/components/hub/sub/DatabaseSourceItem.vue'

const route = useRoute()
const hubId = parseInt(route.query.id)

const hub = ref(null)
const drawer = ref(false)
const allowFile = ["application/pdf", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
const fileList = ref([])

const fileSouce = ref([])
const databseSource = ref([])
const activeName = ref("file")

const databaseForm = ref({
    ip: "",
    port: 3306,
    database: "test",
    type: "mysql",
    username: "root",
    password: "123456",
    hubId: "",
})

async function queryHub() {
    let res = await service.post("/hub/query", { "hubId": hubId })
    console.log(res)
    if (res.status != 200) {
        ElMessage({
            message: '操作失败: ' + res.status,
            type: 'error'
        })
        return
    }

    if (res.data.code != '0') {
        ElMessage({
            message: res.data.code,
            type: "warning"
        })
        return
    } else {
        hub.value = res.data.data
        return
    }
}

async function queryFile() {
    let res = await service.post("/file/querys", { "hubId": hubId })
    console.log(res)
    if (res.status != 200) {
        ElMessage({
            message: '操作失败: ' + res.status,
            type: 'error'
        })
        return
    }

    if (res.data.code != '0') {
        ElMessage({
            message: res.data.code,
            type: "warning"
        })
        return
    } else {
        fileSouce.value = res.data.data
        return
    }
}

async function queryDatabase() {
    let res = await service.post("/database/querys", { "hubId": hubId })
    console.log(res)
    if (res.status != 200) {
        ElMessage({
            message: '操作失败: ' + res.status,
            type: 'error'
        })
        return
    }

    if (res.data.code != '0') {
        ElMessage({
            message: res.data.code,
            type: "warning"
        })
        return
    } else {
        databseSource.value = res.data.data
        return
    }
}

onBeforeMount(async () => {
    await Promise.all([
        queryHub(),
        queryFile(),
        queryDatabase()
    ]);
})

async function submitDatabase() {

    const iptest = /^(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/;
    if (!iptest.test(databaseForm.value.ip)) {
        ElMessage.error('IP地址信息不合规，请检查！');
        return false;
    }
    const porttest = /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
    if (!porttest.test(databaseForm.value.port + "")) {
        ElMessage.error('端口信息不合规，请检查！');
        return false;
    }

    if (databaseForm.value.database.length >= 255) {
        ElMessage.error('数据库名称太长！');
        return false;
    }

    if (databaseForm.value.username.length >= 255) {
        ElMessage.error('数据用户名称太长！');
        return false;
    }

    if (databaseForm.value.password.length >= 255) {
        ElMessage.error('数据库密码名称太长！');
        return false;
    }

    databaseForm.value['hubId'] = hubId

    let res = await service.post("/database/create", databaseForm.value)
    console.log(res)
    if (res.status != 200) {
        ElMessage({
            message: '操作失败: ' + res.status,
            type: 'error'
        })
        return
    }

    if (res.data.code != '0') {
        ElMessage({
            message: res.data.msg,
            type: "warning"
        })
        return
    } else {
        ElMessage.success("添加数据库成功！")
        await queryDatabase()
        return
    }


}

function addDataSource() {
    drawer.value = true
}

// 后面完善吧
async function deleteHub() {

}


const submitUpload = async () => {
    if (fileList.value.lenght == 0) {
        ElMessage.error("上传文件为空")
        return
    }
    console.log(fileList)
    const file = fileList.value[0]
    console.log(file.raw.type)
    console.log(fileList.value)

    let typeBool = false

    for (let index in allowFile) {
        if (file.raw.type == allowFile[index]) {
            typeBool = true;
        }
    }

    if (!typeBool) {
        fileList.value = []
        ElMessage.error("不支持的文件类型")
        return false
    }

    let formData = new FormData()
    formData.append("file", file.raw)
    formData.append("hubId", hubId)
    let res = await service.post("/upload/document", formData, {
        "Content-Type": "multipart/form-data;charset=utf-8"
    })
    console.log(res)

    if (res.status != 200) {
        ElMessage({
            message: '操作失败: ' + res.status,
            type: 'error'
        })
        return
    }

    if (res.data.code != '0') {
        console.log(res.data)
        ElMessage({
            message: res.data.msg,
            type: "warning"
        })
        return
    } else {
        ElMessage({
            message: "文件上传成功",
            type: "success"
        })
        await queryFile()
        return
    }
}

</script>
<template>
    <div id="outer">
        <el-drawer v-model="drawer" title="添加数据源" :with-header="true">
            <div id="drawer">
                <div>{{}}</div>
                <el-tabs v-model="activeName" class="tabs">
                    <el-tab-pane label="上传文档" name="file">
                        <div style="color: rgb(120, 120, 120); margin-top: 2em; margin-bottom: 1.5em;">
                            支持pdf、doc、docx、txt、ppt等文件内容
                        </div>
                        <el-upload action="None" :limit="1" :auto-upload="false" v-model:file-list="fileList">
                            <template #trigger>
                                <el-button type="primary">选择文件</el-button>
                            </template>
                            <el-button style="margin-left: 10px" type="success" @click="submitUpload">
                                上传
                            </el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="上传数据库" name="database">
                        <el-form v-model="databaseForm">
                            <el-form-item label="数据库地址">
                                <el-input v-model="databaseForm.ip" placeholder="请输入数据库IP地址" />
                            </el-form-item>
                            <el-form-item label="数据库端口">
                                <el-input v-model.number="databaseForm.port" placeholder="请输入数据库IP地址" />
                            </el-form-item>
                            <el-form-item label="数据库名称">
                                <el-input v-model="databaseForm.database" placeholder="请输入数据库名" />
                            </el-form-item>
                            <el-form-item label="数据库类型">
                                <el-select v-model="databaseForm.type">
                                    <el-option key="mysql" value="mysql" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="数据库账号">
                                <el-input v-model="databaseForm.username" placeholder="请输入数据库连接用户" />
                            </el-form-item>
                            <el-form-item label="数据库密码">
                                <el-input v-model="databaseForm.password" type="passwrod" placeholder="请输入数据库用户对应密码"
                                    show-password />
                            </el-form-item>
                        </el-form>
                        <div>
                            <el-button style="margin-left: 10px" type="success" @click="submitDatabase" :icon="Plus">
                                添加数据库
                            </el-button>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-drawer>
        <div class="rowItem">
            <div class="datasourceListTitle">
                数据源列表
            </div>
            <div class="datasourceList">
                <FileSourceItem id="SourceItemStyle" v-for="file in fileSouce" :key="file.id" :file="file" />
                <DatabaseSourceItem id="SourceItemStyle" v-for="database in databseSource" :key="database.id"
                    :database="database" />
            </div>
        </div>
        <div class="rowItem">
            <div class="datasourceListTitle">
                知识库信息
            </div>
            <div id="form" v-if="hub != null">
                <el-form-item label="知识库名称">
                    <el-input v-model="hub.hub_name" disabled></el-input>
                </el-form-item>
                <el-form-item label="知识库描述">
                    <el-input type="textarea" v-model="hub.description" disabled></el-input>
                </el-form-item>
                <el-form-item label="切分块大小">
                    <el-input v-model="hub.chunk_size" disabled></el-input>
                </el-form-item>
                <el-form-item label="重叠块大小">
                    <el-input v-model="hub.overlap" disabled></el-input>
                </el-form-item>
                <el-form-item label="隶属群组名">
                    <el-input v-model="hub.group_name" disabled></el-input>
                </el-form-item>
                <el-form-item label="创建者昵称">
                    <el-input v-model="hub.nickname" disabled></el-input>
                </el-form-item>
                <el-form-item label="创 建 时 间">
                    <el-input v-model="hub.create_at" disabled></el-input>
                </el-form-item>
            </div>
            <div id="bottomButtonOuter">
                <el-button type="info" @click="addDataSource" :icon="Upload"> 添加数据源</el-button>
                <el-button v-if="false" type="danger" @click="deleteHub" :icon="Delete">删除知识库</el-button>
            </div>
        </div>
    </div>
</template>
<style scoped>
#outer {
    margin: auto;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    font-weight: 900;
}

.rowItem {
    width: 49%;
    height: 100%;
    box-shadow: var(--el-box-shadow-lighter);
}

.datasourceListTitle {
    text-align: center;
    font-size: 2em;
    padding: 0.1em;
    height: 10%;
}

.datasourceList {
    display: flex;
    flex-direction: row;
    align-items: start;
    justify-content: start;
    flex-flow: row wrap;
    height: 88%;
    overflow: auto;

}

#SourceItemStyle {
    width: 45%;
    height: 50%;
    margin-left: 3%;
    margin-bottom: 2%;
    border: 2px solid rgb(120, 120, 120);
}



#form {
    width: 80%;
    margin: auto;
    margin-top: 2em;
}

#bottomButtonOuter {
    width: 80%;
    margin: auto;
    display: flex;
    justify-content: flex-end;
}
</style>